package daos.auto.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import model.entities.Auto;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import daos.AbstractDAO;
import daos.auto.AutoDAO;

public class AutoDAOJdbcTemplateImpl extends AbstractDAO implements AutoDAO{

	private JdbcTemplate jdbcTemplate;

	public void insert(Auto auto) throws SQLException {
		
		String insertSql = "INSERT INTO AUTOS (MODELO, PATENTE, COLOR, MARCA, DETALLE) VALUES (?,?,?,?,?)";
		Object[] parameters = {auto.getModelo(), auto.getPatente(), auto.getColor(), auto.getMarca(), auto.getDetalle()};
		jdbcTemplate.update(insertSql,parameters);

		System.out.println(insertSql);
		System.out.println("Row inserted OK");
	}
	
	public void delete(Auto auto) throws SQLException {
		String deleteSql = "DELETE FROM AUTOS WHERE PATENTE = ?";
		jdbcTemplate.update(deleteSql, auto.getPatente());
		
		System.out.println(deleteSql);
		System.out.println("Row deleted OK");
	}
	
	public List<Auto> selectAll() throws SQLException {
		String selectSql = "SELECT * FROM AUTOS";
		List<Auto> autoSeleccionados = jdbcTemplate.query(selectSql, getRowMapper());

		System.out.println(selectSql);
		System.out.println("Row selected OK");
		
		return autoSeleccionados;
	}
	
	public Auto selectByPatente(Auto auto) throws SQLException {
		String selectSql = "SELECT * FROM AUTOS WHERE PATENTE = ?";
		Auto autoSeleccionado = jdbcTemplate.queryForObject(selectSql, getRowMapper(), auto.getPatente());

		System.out.println(selectSql);
		System.out.println("Row selected OK");
		
		System.out.println(autoSeleccionado);
		
		return autoSeleccionado;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public RowMapper<Auto> getRowMapper(){
		return new RowMapper<Auto>(){
			public Auto mapRow(ResultSet rs, int arg1) throws SQLException {
				Auto autoSeleccionado = new Auto();
				
				autoSeleccionado.setModelo(rs.getInt("MODELO"));
				autoSeleccionado.setPatente(rs.getString("PATENTE"));
				autoSeleccionado.setColor(rs.getString("COLOR"));
				autoSeleccionado.setMarca(rs.getString("PATENTE"));
				autoSeleccionado.setDetalle(rs.getString("DETALLE"));
				
				return autoSeleccionado;
			}};
	}
}
